package com.wxg.httpclient;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.wxg.domain.englishword.Englishword;
import com.wxg.domain.englishword.Wordexplain;
import com.wxg.service.EnglishWordService;

/**
 * 
 * 从有道词典获取单词释义！
 * 
 * 
 * @author pactera
 *
 */
public class ObtainEnglishWordExplain {

	private static final Logger log = LoggerFactory.getLogger(ObtainEnglishWordExplain.class);
	
	/**
	 * 
	 * @param word
	 * @return 可能返回null
	 */
	public List<String> obtainExplain(String word){
		List<String> resultList = null;
		
		EnglishWordService service = new EnglishWordService();
		List<Wordexplain> list0 = service.findExplainsByWord(word);
		if(null != list0 && list0.size() > 0){
			resultList = new ArrayList<String>();
			for(Wordexplain wp : list0){
				resultList.add(wp.getExplain());
			}
			if(log.isInfoEnabled()){
				log.info("=== 从数据库sqlite中查询单词释义！ ===");
			}
			return resultList;
		}
		
		String tpl = "http://fanyi.youdao.com/openapi.do?keyfrom=ExplainEnglishWord&key=716753987&type=data&doctype=json&version=1.1&q={1}";
		String url = tpl.replace("{1}", word);
		String result = obtainExplainFromYoudao(url);
		
		
		JSONObject entity = JSON.parseObject(result);
		if(JSONPath.contains(entity, "$.basic.explains")){
			resultList = new ArrayList<String>();
			JSONArray arr = (JSONArray)JSONPath.eval(entity, "$.basic.explains");
			if(null != arr){
				for(Object obj : arr){
					resultList.add(obj.toString());
				}
				List<Wordexplain> explainList = new ArrayList<Wordexplain>();
				Englishword ew = service.findByWord(word);
				// 1. 遇到一个Bug: ew 空指针异常！(如果ew为null,等待下一次查询时保存)
				// 2. 这里空指针,可能是清理数据库后没有清理音频文件导致的。(所以还是将音频保存为blob是最好的)
				if(null != ew){
					for(String str : resultList){
						Wordexplain explain = new Wordexplain();
						explain.setWord(word);
						explain.setExplain(str);
						explain.setWordId(ew.getId());
						explainList.add(explain);
					}
					service.addExplains(explainList);
				}
			}
			if(log.isDebugEnabled()){
				log.debug("=== 调用有道API获取单词释义！ ===");
			}
		}
		
		return resultList;
	}
	
	
	public static void main(String[] args) {
		test1();
	}
	
	public static void test1(){
		String url = "http://fanyi.youdao.com/openapi.do?keyfrom=ExplainEnglishWord&key=716753987&type=data&doctype=json&version=1.1&q=good";
		String result = obtainExplainFromYoudao(url);
		
		System.out.println("===");
		JSONObject entity = JSON.parseObject(result);
		if(JSONPath.contains(entity, "$.basic.explains")){
			JSONArray arr = (JSONArray)JSONPath.eval(entity, "$.basic.explains");
			if(null != arr){
				for(Object obj : arr){
					System.out.println( obj.toString() );
				}
			}
		}
		
		System.out.println("===");
		System.out.println(result);
	}
	
	public static void test0(){
		String url = "http://fanyi.youdao.com/openapi.do?keyfrom=ExplainEnglishWord&key=716753987&type=data&doctype=json&version=1.1&q=good";
		JSONObject rootJsonObject = new JSONObject();
		String json = rootJsonObject.toString();
		String result = obtainExplainFromYoudao(url, json);
		System.out.println(result);
	}
	
	public static String obtainExplainFromYoudao(String url, String json){
		String result = "";
		CloseableHttpClient httpclient = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			StringEntity se = new StringEntity(json, Charset.forName("UTF-8"));
			se.setContentType("application/json");
			httpPost.setEntity(se);
			CloseableHttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			httpclient.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return result;
	}
	
	/**
	 * 
	 * @param url
	 * @return
	 */
	public static String obtainExplainFromYoudao(String url){
		String result = "";
		CloseableHttpClient httpclient = null;
		try {
			try {
				httpclient = HttpClients.createDefault();
				HttpPost httpPost = new HttpPost(url);
				httpPost.addHeader("Content-type", "application/json; charset=utf-8");
				httpPost.setHeader("Accept", "application/json");
				CloseableHttpResponse response = httpclient.execute(httpPost);
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
				}
			} finally {
				if(null != httpclient){
					httpclient.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
